﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Serialization;
using Wedo.Recognition.Domain;
using Wedo.Domain.Models;

namespace Wedo.Recognition.Service.CommonService
{
    public class CreateInitData
    {
        private EFDbContext dbContext;
        public Navigations GetXMl()
        {
            XmlSerializer xsr = new XmlSerializer(typeof(Navigations));

            XmlTextReader reader = new XmlTextReader(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Navigation.xml");
            Navigations dd = xsr.Deserialize(reader) as Navigations;
            return dd;
        }


        public void CreateData()
        {
            dbContext = new EFDbContext();
            var xml = GetXMl();

            var ms = xml.Navigation.Select(m => m.Module).Distinct();
            var modules = CreateMoudle(ms);

            var rs = xml.Navigation.Select(m => m.Roles).Distinct();
            var roles = CreateRole(rs);

            foreach (var item in xml.Navigation)
            {
                Resource res = new Resource {
                     Action=item.Action,
                     Controller = item.Controller,
                     Name=item.Page
                     ,Navigator=item.IsNav,
                      Order=item.Order
                };

                res.Module = modules.FirstOrDefault(m => m.Name == item.Module);

                var strRoles = item.Roles.Split(new char[] { ',' }, 
                    StringSplitOptions.RemoveEmptyEntries);
                if (strRoles.Length > 0)
                {
                    var rss = roles.Where(m => strRoles.Any(s => s == m.Id)).ToList();
                    res.Roles = rss;
                }
                dbContext.Resource.Add(res);
                dbContext.SaveChanges();
            }
        }

        private List<Module> CreateMoudle(IEnumerable<string> modules)
        {
            foreach (var item in modules)
            {
                dbContext.Set<Module>().Add(new Module { Name=item });
            }
            dbContext.SaveChanges();

            return dbContext.Set<Module>().ToList();
        }

        private List<Role> CreateRole(IEnumerable<string> datas)
        {
            List<string> list = new List<string>();
            foreach (var item in datas)
            {
                list.AddRange(item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries));
            }

            foreach (var item in list)
            {
                dbContext.Set<Role>().Add(new Role { RoleName = item, Id=item, Description=item });
            }
            dbContext.SaveChanges();

            return dbContext.Set<Role>().ToList();
        }

        
    }
}
